package com.xiaotao.realtimeui.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.LinkedHashMap;

@Component
@ServerEndpoint("/ws")
@Slf4j
public class WsController {
    private static final LinkedHashMap<String, Session> sessionMap = new LinkedHashMap<>();

    @OnOpen
    public void open(Session session) {
        log.info("用户接入");
        sessionMap.put(session.getId(), session);
    }

    @OnClose
    public void close(Session session) {
        log.info("用户退出");
        sessionMap.remove(session.getId());
    }

    public void sendMsg(String msg) {
        sessionMap.forEach((id, session) -> {
            session.getAsyncRemote().sendText(msg);
        });
    }

}
